<template>
  <div style="min-height: 500px">
    <div style="color: gray;font-size: 12px;"> 限制最多添加两组规格</div>
    <div style="display: flex;margin-bottom: 5px">
      <Form v-for="(item, index) in formData" :model="item" label-align="right" v-bind="formItemLayoutWithOutLabel"
        class="solid-border d_form" :ref="setRefs(index)" size="small">

        <div style="display: flex">
          <FormItem :labelCol="{
            xs: { span: 24 },
            sm: { span: 9 },
          }" :wrapperCol="{
            xs: { span: 23 },
            sm: { span: 18 },
          }" name="specName" label="规格名" required="true">
            <Input v-model:value="item.specName" placeholder="请输入规格名" />
          </FormItem>

          <FormItem style="padding-left: 5px;" :labelCol="{
            xs: { span: 24 },
            sm: { span: 18 },
          }" name="hasImgValue" label="添加规格图片">
            <Checkbox v-model:checked="item.hasImgValue"></Checkbox>

          </FormItem>
        </div>

        <FormItem v-for="(domain, d_index) in item.items" :key="domain.key" v-bind="d_index === 0 ? formItemLayout : {}"
          :label="d_index === 0 ? '规格值' : ''" :name="['items', d_index, 'specName']" :rules="{
            required: true,
            message: '规格值不能为空',
            trigger: 'change',
          }">
          <div style="display: flex;">
            <Input v-model:value="domain.specName" placeholder="请输入规格值" style="width: 90%; margin-right: 8px" />
            <div style="display: flex;margin-left: 10px" v-if="item.hasImgValue">
              <span style="align-content: center;width: 45px;">图片：</span>
              <BasicUpload v-model:value="domain.imgValue" v-bind="uploadImgProps"></BasicUpload>

            </div>
            <MinusCircleOutlined v-if="props.isAdd && d_index !== 0
              || domain.isNew
            " class="dynamic-delete-button" :disabled="item.items.length === 1" @click="removeDomain(index, d_index)"
              style="padding-left: 5px" />
          </div>

        </FormItem>
        <FormItem v-bind="formItemLayoutWithOutLabel">
          <Button size="small" style="width: 40%;color: #1c6ca1" @click="addDomain(index)">
            添加规格值
          </Button>
        </FormItem>
        <FormItem v-bind="formItemLayoutWithOutLabel">
          <!--      <Button type="primary" html-type="submit" @click="submitForm">保存</Button>-->
          <Button size="small" v-if="props.isAdd && index != 0" style="margin-left: 10px" @click="deleteGroup(index)">
            删除该规格组
          </Button>
        </FormItem>
      </Form>

    </div>

    <div :style="{ background: 'rgb(190, 200, 200)', paddingBottom: '5px' }">
      <Button size="small" type="primary" v-if="props.isAdd" style="margin-top: 5px;margin-left: 10px;"
        @click="addGroup">
        <PlusOutlined />
        添加规格组
      </Button>
      <Button size="small" v-if="props.isAdd" type="success" style="margin-top: 5px;margin-left: 10px;"
        @click="createSku">
        <RedoOutlined />
        生成sku
      </Button>
      <Button size="small" v-if="!props.isAdd" type="success" style="margin-top: 5px;margin-left: 10px;"
        @click="openTitleModalFn">
        <RedoOutlined />
        重置sku
      </Button>

    </div>
    <Divider>SKU</Divider>
    <div>SKU明细:请单击单元格进行输入</div>
    <div style=" width: 100%; height: 250px;overflow: hidden">
      <VxeBasicTable ref="tableRef" v-bind="gridOptions">

        <template #img_default="{ row, column }">

          <BasicUpload v-model:value="row[column.field]" v-bind="uploadImgProps"></BasicUpload>

        </template>

      </VxeBasicTable>
    </div>


    <div style="width: 100%;text-align: right;">
      <!--      <Button @click="testFn">测试1</Button>-->
      <Button @click="closeFn">关闭</Button> <Button @click="submitFn" type="primary">提交</Button>


    </div>

    <Modal v-model:visible="visible" title="提示信息" @ok="reloadSkuTable">
      <p>重置sku将会替换原有 规格名称,规格图片,原价、售价、重量、体积; 库存则继续保留是否继续?</p>
    </Modal>
  </div>
</template>

<script lang="ts" setup>
import { Form, FormItem, Input, Button, Checkbox, Modal, Divider } from 'ant-design-vue';
import { MinusCircleOutlined, PlusOutlined, RedoOutlined } from '@ant-design/icons-vue';
import { ValidateErrorEntity } from 'ant-design-vue/es/form/interface';
import { BasicUpload, ImageUpload } from '@/components/Upload';
import util from "@/utils/util";
import { useMessage } from '@/hooks/web/useMessage';
import { BasicTable, useTable } from '@/components/Table';
import { getMergeHeaderColumns, getSkuListColumns } from './tableData';
import {
  BasicTableProps,
  log,
  VxeBasicTable,
  VxeGridInstance,
  VxeGridListeners,
} from '@/components/VxeTable';

const { createMessage } = useMessage();
import { useRefs } from '@vben/hooks';

import { ref, watch, onMounted, unref, reactive } from "vue";
import { vxeTableColumns, vxeTableFormSchema } from "@/views/baseInfo/brandList/role.data";
import { uploadImgApi } from "@/api/sys/upload";
import { error } from '@/utils/log';

const { refs, setRefs } = useRefs();

var baseJson = {
  hasImgValue: false,
  items: [
    {
      specName: ""
    }
  ],
}

const uploadImgProps = {
  api: uploadImgApi,
  multiple: true,
  accept: ['.png', '.jpeg', '.jpg'],
  resultField: 'data.data',
  maxSize: '10',
  maxNumber: '30',
}

var baseData = [
  util.copy(baseJson)
]

const visible = ref(false);//生成sku弹层

const isAdd = ref(false);
const formData = ref(util.copy(baseData));
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
};
const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 20, offset: 4 },
  },
};


interface Domain {
  value: string;
  key: number;
}

const props = defineProps({
  value: { type: Object, default: {} },
  isAdd: { type: Boolean, default: false },
  data: { type: Object, default: {} }
});
const baseColumns = getSkuListColumns();
const skuColumns = [...baseColumns];
const tableColumns = ref(skuColumns)

const tableDateList = ref([]);

// const [registerTable] = useTable({
//   title: 'sku明细',
//   bordered: true,
//   showIndexColumn:false,
//   pagination:false,
//   size:"small",
//   maxHeight:500,
//   height:"500px",
//   dataSource: tableDateList,
//   columns: tableColumns
// });

const tableRef = ref<VxeGridInstance>();
var baseEitRules = {
  // costPrice: [
  //   {required: true, message: '必须填写'}
  // ],
  oriPrice: [
    { required: true, message: '必须填写' }
  ],
  skuStocks: [
    { required: true, message: '必须填写' }
  ]
}
const gridOptions = reactive<BasicTableProps>({
  id: 'VxeTable',
  keepSource: true,
  editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  showOverflow: true,
  size: 'mini',
  height: 'auto',
  editRules: util.copy(baseEitRules),
  columns: tableColumns,
  toolbarConfig: {
    enabled: false
    // tools:[]
  },
  proxyConfig: {
    enabled: false
  },

  data: tableDateList


});

const dataValue = ref({});

function openTitleModalFn() {

  if (props.data?.id && tableDateList.value.length > 0) {
    visible.value = true;
  } else {
    createSku()
  }
}

watch(
  () => props.value,
  (data) => {

    try {
      intData(data);

    } catch (e) {
      console.log(e)
    }

  },
);

/**
 * 生成表格列
 * isNewTable 是否刷新表格数据
 */
function createColumnsFn(isNewTable) {
  // specGroupName,specValueName
  // specName
  let list = [];
  let columns = [];

  //合并其他规格
  // console.log("--规格：", formData.value)
  formData.value.forEach(r => {
    r.otherMap = new Map();

    r.items.forEach(x => {
      // map.set(`${r.specName}:${x.specName}`,x.specName);

      formData.value.forEach(r2 => {
        if (r.specName != r2.specName) {
          let n_json = {
            specName: r2.specName,
            items: unref(r2.items)
          }
          r.otherMap.set(r2.specName, n_json);
        }
      })
    });

  });
  // console.log("---formData.value::",formData.value)

  list = getSpecList();



  if (isNewTable) {
    list.forEach(e => {
      e.oriPrice = props.data.oriPrice;
      e.skuStocks = props.data.baseNumber;
    })
    tableDateList.value = list;
    tableRef.value.loadData(list);
  }


  formData.value.forEach(r => {
    //组装列
    // 库存  title: 入库数量， field:skuStocks
    let columnJson = {
      title: '',
      field: '',
      width: 150,
    };
    columnJson.title = r.specName;
    columnJson.field = r.specName;
    columnJson.customCell = (_, index) => ({
      rowSpan: setRowSpan(r, index, r.specName),
    });
    columns.push(columnJson);
  });
  let stockColumn = {
    title: '录入数量',
    field: 'skuStocks',
    editRender: { name: 'VxeInput', props: { type: 'number' } },
    width: 150,
  }
  // console.log("---columns:",columns);
  let d_columns = [...columns,];
  if (props.isAdd) {
    // let json=util.copy(baseEitRules);
    // json.skuStocks=[
    //   {required: true, message: '必须填写'}
    // ]
    // tableRef.value.setEditCell()
    d_columns.push(stockColumn)
  }
  d_columns.push(...skuColumns);
  console.log("---props.isAdd)::", props.isAdd)
  tableColumns.value = d_columns


}



function getSpecList() {
  let list = [];
  //组装数据
  if (formData.value.length > 1) {
    //2组
    let r1 = formData.value[0];
    let r2 = formData.value[1];

    r1.items.forEach(xx => {
      r2.items.forEach(yy => {
        let json = {}
        json[r1.specName] = xx.specName;
        json[r2.specName] = yy.specName;

        /**
         * 体积和重量
         */
        let imgValue = null;
        json.weight = props.data.weight;
        json.weightUnit = props.data.weightUnit;

        json.volume = props.data.volume;
        json.volumeUnit = props.data.volumeUnit;
        let hasSpecPic = 0;
        if (r1.hasImgValue) {
          if (r1.imgValue && r1.imgValue.length > 0) {
            hasSpecPic = 1;
            imgValue = r1.imgValue
          }
        } else if (xx.imgValue && xx.imgValue.length > 0) {
          hasSpecPic = 1;
          imgValue = xx.imgValue;
        }
        json.skuPicValue = imgValue;
        json.specGroupName1 = r1.specName;
        json.specGroupValue1 = xx.specName;
        json.specGroupName2 = r2.specName;
        json.specGroupValue2 = yy.specName;
        json.wmSkuSpecList = [
          {
            specGroupName: r1.specName,
            specName: xx.specName,
            hasSpecPic
          },
          {
            specName: yy.specName,
            specGroupName: r2.specName,

          }
        ]
        list.push(json);
      })

    })
  }
  else {
    //1组
    let r1 = formData.value[0];
    r1.items.forEach(xx => {
      let json = {}
      json[r1.specName] = xx.specName;

      /**
       * 体积和重量
       */
      let imgValue = null;
      json.weight = props.data.weight;
      json.volume = props.data.volume;
      let hasSpecPic = 0;
      if (r1.hasImgValue) {
        if (r1.imgValue && r1.imgValue.length > 0) {
          hasSpecPic = 1;
          imgValue = r1.imgValue
        }
      } else if (xx.imgValue && xx.imgValue.length > 0) {
        hasSpecPic = 1;
        imgValue = xx.imgValue;
      }
      json.skuPicValue = imgValue;
      json.specGroupName1 = r1.specName;
      json.specGroupValue1 = xx.specName;

      json.wmSkuSpecList = [
        {
          specGroupName: r1.specName,
          specName: xx.specName,
          hasSpecPic
        }
      ]
      list.push(json);
    })
  }
  return list;
}

/**
 * 刷新sku表格
 */
function reloadSkuTable() {
  let list = getSpecList();

  // console.log("--list:", list);
  const tableData = tableRef.value.getTableData();
  let productSkuList = tableData.tableData;

  for (let i = 0; i < productSkuList.length; i++) {
    let a_row = productSkuList[i];
    let b_row = list[i];



    for (let key in b_row) {
      // if(key=="skuPicValue"){
      //   debugger
      // }
      //key == "costPrice" || key == "oriPrice"
      if (key == "skuPic" || key == "skuPicValue"
        || key == "status"
      ) {
        if (!a_row[key]) {
          a_row[key] = b_row[key];
        }
        // a_row[key] = b_row[key];

      } else {
        a_row[key] = b_row[key];

      }
    }

    //同步 基础售价
    a_row.costPrice = props.data.costPrice;
    //同步成本价
    if (props.data.oriPrice) {
      a_row.oriPrice = props.data.oriPrice;
    }
  }
  console.log("---productSkuList:", productSkuList);

  //追加的规格
  if (list.length > productSkuList.length) {
    for (let a = 0; a < list.length; a++) {
      if (a > productSkuList.length - 1) {
        let item = list[a];
        item.status = 1;
        productSkuList.push(item);
      }
    }
  }
  visible.value = false;
  tableRef.value.loadData(productSkuList);

}

//规格行合并
function setRowSpan(row, index, specName) {
  let rowSpan = 1;
  return rowSpan;

}

function testFn() {
  formData.value = [
    {
      hasImgValue: false,
      specName: "颜色",
      items: [
        { specName: '蓝' },
        { specName: '红' }
      ]
    },
    {
      hasImgValue: false,
      specName: "尺寸",
      items: [
        { specName: 'L' },
        { specName: 'S' }
      ]
    }
  ];
  createSku();

}

const emit = defineEmits(['change', 'close', 'success']);

function intData(list) {
  // console.log("==list:", list);
  dataValue.value = {};
  formData.value = util.copy(baseData);
  tableDateList.value = [];
  tableRef.value.loadData([]);
  isAdd.value = false;

  if (props.isAdd) {
    isAdd.value = true;
    // console.log("==当前处于新增:");
  } else {
    // console.log("==当前处于修改:");
  }

  if (util.isNotEmpty(list) && list.productSpecList) {
    // if(list?.id){
    //   isAdd.value=false;
    // }
    dataValue.value = list;
    formData.value = list.productSpecList;
    tableDateList.value = list.productSkuList;
    tableRef.value.loadData(tableDateList.value);
    // console.log("==list:", list);
    //装配sku列
    createColumnsFn(false);
  }

}

function deleteGroup(index) {
  formData.value.splice(index, 1);

}

const removeDomain = (index, d_index) => {

  // let index = formData.value.items.indexOf(item);
  if (d_index !== -1) {
    formData.value[index].items.splice(d_index, 1);
  }
};

function addDomain(index) {

  formData.value[index].items.push({ specName: "", isNew: true })

}


function addGroup() {

  if (formData.value.length > 1) {
    createMessage.error("已达到规格组上限");
    return false;
  }
  formData.value.push(util.copy(baseJson))

}

//生成sku
function createSku() {
  visible.value = false;
  // console.log(refs)
  let refList = refs.value
  let errorList = [];
  refList.forEach(r => {
    r?.validate().then((res) => {
    }).catch((error) => {
      errorList.push(error)
    });
  });
  if (errorList.length > 0) {
    createMessage.error("请将规格信息补充完整");
    return false;
  }
  createColumnsFn(true);
}


async function submitFn() {
  let pass = checkStatus();
  pass.then(res => {
    const tableData = tableRef.value.getTableData();

    let subJson = {};
    let productSkuList = tableData.tableData;
    productSkuList.forEach(r => {
      r.skuPic = null;
      if (r.skuPicValue.length > 0) {
        r.skuPic = r.skuPicValue.join(",");
      }
    })
    let productSpecList = formData.value;

    // console.log("---规格信息:",formData.value);
    // console.log("--sku:",productSkuList);
    subJson = {
      productSpecList, productSkuList
    }
    //productSkuList
    emit("success", subJson);
  }).catch(err => {
    createMessage.error(err.msg);

  })





};

function closeFn() {
  emit("close");

}



function checkStatus() {
  let refList = refs.value
  let promiseArr = [];

  refList.forEach(r => {
    let p = new Promise((reslove, reject) => {
      r?.validate().then(() => {
        reslove({ msg: "规格表格校验通过" })
      }).catch(error => {
        reject({ msg: "请将规格信息补充完整！" })
      })
    })
    promiseArr.push(p)

  });

  let sku_p = new Promise((reslove, reject) => {
    tableRef.value.validate(true).then(res => {
      if (!res) {
        reslove({ msg: "sku表格校验通过" })
      } else {
        reject({ msg: "请将SKU表格信息补充完整！" })
      }
    });

  });

  promiseArr.push(sku_p)



  return Promise.all(promiseArr)

  // let isError=false;


  //   if (isError) {
  //     createMessage.error("请将规格信息补充完整");
  //     return false;
  //   }
  //   const errMap = await tableRef.value.validate(true)
  //   if (errMap) {
  //     createMessage.error("请将sku信息补充完整");
  //     return false;
  //   } else {
  //   }
}

</script>

<style scoped>
.d_form {
  width: 50%;
}

.solid-border {
  margin-right: 5px;
  padding: 4px;
  border-width: 1px;
  border-style: solid;
  border-radius: 4px;

  /* 可以根据需要调整边框的粗细 */
  border-color: #d0d0d0;

  /* 可以根据需要调整边框的颜色 */
}
</style>
